/*
题目：合并k个升序链表
给你一个链表数组，每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中，返回合并后的链表。
 */
public class MergeKLists {
    public ListNode merge(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode();
        ListNode temp = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                dummy.next = list1;
                list1 = list1.next;
            } else {
                dummy.next = list2;
                list2 = list2.next;
            }
            dummy = dummy.next;
        }
        if (list1 != null) {
            dummy.next = list1;
        }
        if (list2 != null) {
            dummy.next = list2;
        }
        return temp.next;
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0)  return null;
        if (lists.length == 1)  return lists[0];
        ListNode cmp = lists[0];
        for (int i = 1; i < lists.length; i++) {
            cmp = this.merge(cmp, lists[i]);
        }
        return cmp;
    }
}
